﻿using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Scrabble.Controls
{
    public class DragAdorner : Adorner
    {
        private readonly Rectangle _child;
        private Vector _offset;

        public DragAdorner(UIElement adornedElement, Size size, Brush brush) : base(adornedElement)
        {
            _child = new Rectangle { Fill = brush, Width = size.Width, Height = size.Height, IsHitTestVisible = false };
        }

        public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
        {
            var result = new GeneralTransformGroup();
// ReSharper disable AssignNullToNotNullAttribute
            result.Children.Add(base.GetDesiredTransform(transform));
// ReSharper restore AssignNullToNotNullAttribute
            result.Children.Add(new TranslateTransform(_offset.X, _offset.Y));
            return result;
        }

        public Vector Offset 
        { 
            get { return _offset; } 
            set
            {
                _offset = value;
                UpdateLocation();
            }
        }

        protected override Size MeasureOverride(Size constraint)
        {
            _child.Measure(constraint);
            return _child.DesiredSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            _child.Arrange(new Rect(finalSize));
            return finalSize;
        }

        protected override Visual GetVisualChild(int index)
        {
            return _child;
        }

        protected override int VisualChildrenCount
        {
            get { return 1; }
        }

        private void UpdateLocation()
        {
            var adornerLayer = Parent as AdornerLayer;
            if (adornerLayer != null) adornerLayer.Update(AdornedElement);
        }
    }
}